package main

import (
	"context"
	"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"log"
	"net"
	"net/http"
	"sgrpc/grpc/proto/hello"
	"sgrpc/grpc/server/interceptor"
	"sgrpc/grpc/server/service"
)

func main() {

	// 串联一元rpc拦截器
	unaryInterceptorChain := grpc.ChainUnaryInterceptor(interceptor.UnaryLoggerInterceptor)

	// 串联流式rpc拦截器
	streamInterceptorChain := grpc.ChainStreamInterceptor(interceptor.StreamLoggerInterceptor)

	server := grpc.NewServer(grpc.Creds(insecure.NewCredentials()), unaryInterceptorChain, streamInterceptorChain)

	helloService := new(service.HelloService)

	hello.RegisterHelloServiceServer(server, helloService)

	listen, err := net.Listen("tcp", "127.0.0.1:8000")
	if err != nil {
		log.Fatal(err)
	}

	go server.Serve(listen)

	// 启动网关
	StartGrpcGatewayServer()
}

// 启动网关服务

func StartGrpcGatewayServer() error {

	opts := []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}
	serveMux := runtime.NewServeMux()
	err := hello.RegisterHelloServiceHandlerFromEndpoint(context.Background(), serveMux, "127.0.0.1:8000", opts)
	if err != nil {
		return err
	}

	return http.ListenAndServe("127.0.0.1:9000", serveMux)
}
